package com.wyl.template.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * @Auther: wyl
 * @Date: 2021/6/22
 * @Description:
 */
@Slf4j
public class ParamUtils {

    private final static String ID_NUMBER="ID_NUMBER";

    /**
     * 构造分页参数
     *
     * @param current   页码
     * @param pageSize  数量
     * @param sortParam 排序字段
     * @param direction 排序方向 1=asc
     * @param order     是否排序
     * @param <O>
     * @return
     */
    public static <O> Page<O> getPage(Integer current, Integer pageSize, String sortParam, Integer direction, boolean order) {
        Page<O> p = new Page<>();
        p.setCurrent(current);
        p.setSize(pageSize);
        if (order) {
            OrderItem orderItem = null;
            if (StringUtils.hasText(sortParam)) {
                if (direction == 1) {
                    orderItem = OrderItem.asc(sortParam);
                } else {
                    orderItem = OrderItem.desc(sortParam);
                }
            } else {
                orderItem = OrderItem.asc("id");
            }
            p.addOrder(orderItem);
        }
        return p;
    }

    /**
     * 构造QueryWrapper
     * @param className
     * @param param
     * @param <T>
     * @return
     */
    public static <T> QueryWrapper<T> getParamWrapper(String className, String param)  {
        if (!StringUtils.hasLength(param)) {
            return new QueryWrapper<>();
        }
        JSONObject jsonObject = null;
        Class<?> aClass = null;
        try {
            aClass = Class.forName(className);
            if (aClass == null) {
                return new QueryWrapper<>();
            }

            jsonObject = JSONObject.parseObject(param);
        } catch (Exception e) {
            log.error("queryWrapper反射错误", e.getMessage());
            e.printStackTrace();
        }
        if (jsonObject == null) {
            return new QueryWrapper<>();
        }
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();

        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
//            System.out.println(field.getName()+"-_-"+field.getType().getName());
            String fieldName = field.getName();
            String fieldType = field.getType().getName();
            Object obj = jsonObject.get(fieldName);
            if (!ObjectUtils.isEmpty(obj)) {

                // 驼峰转下划线 loginName -> login_name
                String dbFieldName = CommonUtil.humpToUnderline(fieldName);
//                System.err.println(dbFieldName);
                if ("java.lang.Long".equals(fieldType) || "java.lang.Integer".equals(fieldType)) {
                    queryWrapper.eq(dbFieldName, Long.valueOf(obj.toString()));
                } else if ("java.lang.String".equals(fieldType)) {
                    //若是身份证，要加密前台传过来的身份证
                    //由于加密算法，只能完全匹配，不能like
                    if(ID_NUMBER.equals(dbFieldName)){
                        String idNumber = null;
                        try {
                            idNumber = Des3New.encodeCBC(obj.toString());
                        } catch (Exception e) {
                            log.error("加密身份证失败",e.getMessage());
                        }
                        queryWrapper.eq(dbFieldName, idNumber);
                    }else{
                        queryWrapper.like(dbFieldName, obj.toString());
                    }
                } else if ("java.util.Date".equals(fieldType)) {
                    if (obj instanceof JSONArray) {
                        JSONArray jsonArray = (JSONArray) obj;

                        if (jsonArray.size() <= 1) {
                            queryWrapper.eq(dbFieldName, DateUtils.pareToDateAuto(obj.toString()));
                            continue;
                        }

                        Date start = DateUtils.pareToDateAuto(jsonArray.get(0).toString());
                        Date end = DateUtils.pareToDateAuto(jsonArray.get(1).toString());

                        if (start.equals(end)) {
                            queryWrapper.eq(dbFieldName, start);
                            continue;
                        }
                        if (start != null) {
                            queryWrapper.ge(dbFieldName, start);
                        }
                        if (end != null) {
                            queryWrapper.le(dbFieldName, end);
                        }

                    } else {
                        queryWrapper.eq(dbFieldName, DateUtils.pareToDateAuto(obj.toString()));
                    }
                }
            }


        }

        return queryWrapper;
    }


    public static void main(String[] args) throws Exception {
        // 运行main方法，需要去掉@Slf4j注解
        String className = "com.wyl.template.domain.model.SysUserDO";
        String param = "{\"id\":1,\"userName\":\"root\",\"createTime\":[\"2021-06-21 11:11:11\",\"2021-06-22 12:12:12\"]}";
        ParamUtils.getParamWrapper(className, param);
    }
}
